package com.tutu.service.impl;

import com.tutu.core.Constant;
import com.tutu.message.TextMessage;
import com.tutu.service.CoreService;
import com.tutu.service.UserService;
import com.tutu.utils.BaseUtil;
import com.tutu.utils.weixin.MessageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * CoreServiceImpl
 * Created by 涂奕恒 on 2022/3/2 15:59.
 */
@Service
public class CoreServiceImpl implements CoreService {

    @Autowired
    UserService userService;

    @Override
    public String processRequest(HttpServletRequest request) {
        String respMessage = null;

        try {
            // 默认返回的文本消息内容
            String respContent = "未知的消息类型！";

            // xml请求解析
            Map<String, String> requestMap = MessageUtil.parseXml(request);

            // 发送方帐号（open_id）
            String fromUserName = requestMap.get("FromUserName");

            // 公众账号
            String toUserName = requestMap.get("ToUserName");

            // 消息类型
            String msgType = requestMap.get("MsgType");

            // 回复文本消息
            TextMessage textMessage = new TextMessage();
            textMessage.setToUserName(fromUserName);
            textMessage.setFromUserName(toUserName);
            textMessage.setCreateTime(System.currentTimeMillis());
            textMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
            textMessage.setFuncFlag(0);

            switch (msgType) {
                // 文本消息
                case MessageUtil.RESP_MESSAGE_TYPE_TEXT:
                    respContent = "我不太懂您的意思欸...";
                    break;
                // 图片消息
                case MessageUtil.RESP_MESSAGE_TYPE_IMAGE:
                    respContent = "百度识图，识您所见";
                    break;
                // 语音消息
                case MessageUtil.RESP_MESSAGE_TYPE_VOICE:
                    respContent = "真心话大冒险么？";
                    break;
                // 视频消息
                case MessageUtil.RESP_MESSAGE_TYPE_VIDEO:
                    respContent = "哇哦~";
                    break;
                // 视频消息
                case MessageUtil.RESP_MESSAGE_TYPE_SHORTVIDEO:
                    respContent = "嘘！";
                    break;
                // 地理位置消息
                case MessageUtil.RESP_MESSAGE_TYPE_LOCATION:
                    respContent = "杲恴地图时刻为您导航~";
                    break;
                // 链接消息
                case MessageUtil.RESP_MESSAGE_TYPE_LINK:
                    respContent = "警告！！非法网站，请勿打开！！";
                    break;
                // 事件推送
                case MessageUtil.RESP_MESSAGE_TYPE_EVENT:
                    // 事件类型
                    String eventType = requestMap.get("Event");

                    // 订阅
                    switch (eventType) {
                        case MessageUtil.EVENT_TYPE_SUBSCRIBE:
                            respContent = "您好，欢迎关注嘉润AI数据监控平台，您可以在 个人中心-我的信息 里面完善您的个人信息，享受我们为您提供的智能实时数据监控及预警服务";

                            // 同时校验该用户是否完善过个人信息
                            userService.userSubscribe(fromUserName, true);
                            break;
                        // 取消订阅
                        case MessageUtil.EVENT_TYPE_UNSUBSCRIBE:
                            // 取消订阅后用户再收不到公众号发送的消息，因此不需要回复消息
                            userService.userSubscribe(fromUserName, false);
                            break;
                        // 扫描带参数二维码
                        case MessageUtil.EVENT_TYPE_SCAN:
                            // TODO 处理扫描带参数二维码事件
                            break;
                        // 上报地理位置
                        case MessageUtil.EVENT_TYPE_LOCATION:
                            // TODO 处理上报地理位置事件
                            break;
                        // 自定义菜单点击事件
                        case MessageUtil.EVENT_TYPE_CLICK:
                            // 事件KEY值，与创建自定义菜单时指定的KEY值对应
                            String eventKey = requestMap.get("EventKey");

                            switch (eventKey) {
                                case Constant.EVENT_PROJECT_LIST:
                                    respContent = getProjectList(fromUserName);
                                    break;
                                case Constant.EVENT_PERSON_INFO:
                                    respContent = "我的信息菜单项被点击！";
                                    break;
                                case Constant.EVENT_CURRENT_MSG:
                                    respContent = "实时数据菜单项被点击！";
                                    break;
                                case Constant.EVENT_HISTORY_MSG:
                                    respContent = "历史数据菜单项被点击！";
                                    break;
                                case Constant.EVENT_ALARM_MSG:
                                    respContent = "预警消息菜单项被点击！";
                                    break;
                                case Constant.EVENT_ABOUT_US:
                                    respContent = "关于我们菜单项被点击！";
                                    break;
                                case Constant.EVENT_CONTACT_US:
                                    respContent = getContactUsInfo();
                                    break;
                            }
                            break;
                    }
                    break;
            }

            if (BaseUtil.isNotBlank(respContent)) {
                textMessage.setContent(respContent);
                respMessage = MessageUtil.textMessageToXml(textMessage);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return respMessage;
    }

    private String getProjectList(String openId) {
        StringBuilder str = new StringBuilder();

        /*for (ProjectUser projectUser : projectUserDao.findListByUserOpenId(openId)) {
            str.append("项目：");
            str.append(projectUser.getProject().getCompany().getName());
            str.append(projectUser.getProject().getName());
            str.append("\r\n");
            str.append("到期日期：");
            str.append(DateUtils.longToStringWithFormat(projectUser.getProject().getCompany().getEndTime(), Constant.TIME_FORMAT_DEFAULT));
            str.append("\r\n");
            str.append("====================");
            str.append("\r\n");
        }*/

        if (str.length() > 0) {
            return str.substring(0, str.lastIndexOf("\r\n"));
        } else {
            return "暂无关联项目，请联系管理员添加";
        }
    }

    private String getContactUsInfo() {
        return "黄石市嘉润信息科技有限公司\r\n19907239381\r\n18953174701";
    }
}
